package open189.sign;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.Properties;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.joda.time.DateTime;
import org.shiro.demo.entity.SmsToken;
import org.shiro.demo.service.IBaseService;
import org.shiro.demo.service.ISmsTokenService;
import org.springframework.core.io.DefaultResourceLoader;

public class SmsSender {
	@Resource(name = "smsTokenService")
	private ISmsTokenService smsTokenService;
	private static DefaultResourceLoader loader = new DefaultResourceLoader();
	private static Properties prop = new Properties();
	static {
		try {
			prop.load(loader.getResource("classpath:sms.properties").getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * {"res_code":"0","res_message":"Success","access_token":
	 * "b286febd2a8174a6ababcfe65800f07d1406709153083","expires_in":2592000}
	 * 有效期是30天，验证时间是2014年7月30号
	 * 
	 * @param random
	 * @return
	 * @throws Exception
	 */

	public boolean postSMS(String random, String phone) throws Exception {
		SmsToken smstoken = smsTokenService.get(1);
		if(smstoken.getExpiredTime().after(new Date())) {//  已经过期，更新数据
			smstoken = smsTokenService.update(1);
		}
		BufferedReader reader = null;
		HttpURLConnection connection = null;
		try {
			// 发送手机 短消息
			URL postUrl = new URL("http://api.189.cn/v2/emp/templateSms/sendSms");
			// 打开连接
			connection = (HttpURLConnection) postUrl.openConnection();
			// acceptor_tel=13123185312&template_id=91000001&template_param={"日报":"nihao","晚报":"nidao","url":"www.baidu.com"}&app_id=418839000000031xxx&access_token=c49fabf158e25985ed1284a75716a9b9137067210xxxx&timestamp=2013-09-06+16%3A07%3A42
			// http正文内，因此需要设为true
			connection.setDoOutput(true);
			// Read from the connection. Default is true.
			connection.setDoInput(true);
			// Set the post method. Default is GET
			connection.setRequestMethod("POST");
			// Post cannot use caches
			// Post 请求不能使用缓存
			connection.setUseCaches(false);
			// connection.setRequestProperty("Content-Type",
			// "application/json");
			// 要注意的是connection.getOutputStream会隐含的进行connect。
			connection.connect();
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
			// The URL-encoded contend
			// 正文，正文内容其实跟get的URL中'?'后的参数字符串一致
			// 2014-08-04+15%3A45%3A40
			DateTime dt = new DateTime();
			String time = dt.plusMinutes(2).toString("yyyy-MM-dd HH:mm:ss");
			// phone="15201967267";
			String content = "acceptor_tel=" + phone + "&template_id=" + prop.getProperty("template_id") + "&template_param={\"param1\":\"x\",\"param2\":\"" + random + "\",\"param3\":\"10分钟\"}&app_id=" + prop.getProperty("app_id") + "&access_token=" + smstoken.getToken() + "&timestamp=" + time;

			// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
			out.write(content.getBytes("utf-8"));

			out.flush();
			out.close(); // flush and close
			reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			StringBuilder result = new StringBuilder();
			System.out.println("=============================");
			System.out.println("Contents of post request");
			System.out.println("=============================");
			while ((line = reader.readLine()) != null) {
				// System.out.println(line);
				result.append(line);
			}
			System.out.println("=============================");
			System.out.println("Contents of post request ends");
			System.out.println("=============================");
			JSONObject jb = JSONObject.fromObject(result.toString());
			int returnCode = (Integer) jb.get("res_code");
			if (returnCode != 0) {
				System.out.println(result.toString());
				// 更新token。。token
				if(returnCode==110){// 更新token
					smsTokenService.update(1);
				}
				return false;
			}
			reader.close();
			connection.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			if (reader != null) {
				reader.close();
			}
			if (connection != null) {
				connection.disconnect();
			}
		}
		return true;
		// 成功{"res_code":"0","res_message":"Success","idertifier":"90610730164302806669"}
		// 成功{"res_code":"0","res_message":"Success","idertifier":"90610730165225806924"}
	}

	/**
	 * 
	 * @param 只发送密码
	 *            。
	 * @return
	 * @throws Exception
	 */

	public boolean postSMS1(String password, String phone) throws Exception {
		BufferedReader reader = null;
		HttpURLConnection connection = null;
		try {
			// 发送手机 短消息
			URL postUrl = new URL("http://api.189.cn/v2/emp/templateSms/sendSms");
			// 打开连接
			connection = (HttpURLConnection) postUrl.openConnection();
			// acceptor_tel=13123185312&template_id=91000001&template_param={"日报":"nihao","晚报":"nidao","url":"www.baidu.com"}&app_id=418839000000031xxx&access_token=c49fabf158e25985ed1284a75716a9b9137067210xxxx&timestamp=2013-09-06+16%3A07%3A42
			// http正文内，因此需要设为true
			connection.setDoOutput(true);
			// Read from the connection. Default is true.
			connection.setDoInput(true);
			// Set the post method. Default is GET
			connection.setRequestMethod("POST");
			// Post cannot use caches
			// Post 请求不能使用缓存
			connection.setUseCaches(false);
			// connection.setRequestProperty("Content-Type",
			// "application/json");
			// 要注意的是connection.getOutputStream会隐含的进行connect。
			connection.connect();
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
			// The URL-encoded contend
			// 正文，正文内容其实跟get的URL中'?'后的参数字符串一致
			// 2014-08-04+15%3A45%3A40
			DateTime dt = new DateTime();
			String time = dt.plusMinutes(2).toString("yyyy-MM-dd HH:mm:ss");
			// phone="15201967267";
			// 得到前三位跟后面三位，中间打星三位
			StringBuilder sb = new StringBuilder();
			sb.append(phone.substring(0, 3));
			sb.append("***");
			sb.append(phone.substring(phone.length() - 3));

			String content = "acceptor_tel=" + phone + "&template_id=" + prop.getProperty("getback_template_id") + "&template_param={\"param1\":\"" + sb.toString() + "\",\"param2\":\"" + password + "\"}&app_id=" + prop.getProperty("app_id") + "&access_token=" + prop.getProperty("access_token") + "&timestamp=" + time;

			// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
			out.write(content.getBytes("utf-8"));

			out.flush();
			out.close(); // flush and close
			reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			StringBuilder result = new StringBuilder();
			System.out.println("=============================");
			System.out.println("Contents of post request");
			System.out.println("=============================");
			while ((line = reader.readLine()) != null) {
				System.out.println(line);
				result.append(line);
			}
			System.out.println("=============================");
			System.out.println("Contents of post request ends");
			System.out.println("=============================");
			//
			JSONObject jb = JSONObject.fromObject(result.toString());
			int returnCode = (Integer) jb.get("res_code");
			if (returnCode != 0) {
				System.out.println(result.toString());
				return false;
			}

			reader.close();
			connection.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			if (reader != null) {
				reader.close();
			}
			if (connection != null) {
				connection.disconnect();
			}
		}
		return true;
		// 成功{"res_code":"0","res_message":"Success","idertifier":"90610730164302806669"}
		// 成功{"res_code":"0","res_message":"Success","idertifier":"90610730165225806924"}
	}
}
